import {createStore} from "redux"

let cartList=[];
if(localStorage.getItem("mes")){
	cartList=JSON.parse(localStorage.getItem("mes"))
}


const initState={
	shopList:[],
	cartList
}
function reducer(state=initState,action) {
	let newSatate=Object.assign({},state)
	switch(action.type){
		case "SET_SHOP_LIST":
			newSatate.shopList=action.data;
			newSatate=syncData(newSatate)
			return newSatate;
		case "ADD":
			action.item.state=true
			var cartList=[...newSatate.cartList,action.item]
			newSatate.cartList=cartList
			return newSatate;
		case "ADD_COUNT":
			var cartList=[...newSatate.cartList];
			cartList.find(item=>item.id===action.id).count++
			newSatate.cartList=cartList
			newSatate=syncData(newSatate)
			return newSatate;
		case "REDUCE_COUNT":
			var cartList=[...newSatate.cartList];
			var item=cartList.find(item=>item.id===action.id)
			if(item.count===1){
				let index=cartList.findIndex(item=>item.id===action.id)
				cartList.splice(index,1)
			}else{
				item.count--
			}
			newSatate.cartList=cartList
			newSatate=syncData(newSatate)
			return newSatate;
		case "REMOVE":
			var cartList=[...newSatate.cartList];
			let index=cartList.findIndex(item=>item.id===action.id)
			cartList.find(item=>item.id===action.id).count=1
			cartList.splice(index,1)
			newSatate.cartList=cartList
			return newSatate;
		case "DELALLS":
			var shopList=[...newSatate.shopList];
			for(let item of shopList){
				item.count=1;
			}
			newSatate.cartList=[];
			return newSatate;
		default:
			return newSatate;
	}

}

function syncData(state) {
	let cartList=[...state.cartList];
	let shopList=[...state.shopList];
	for(let item of cartList){
		let shopItem=shopList.find(val=>val.id===item.id)
		shopItem.count=item.count;
	}
	state={
		cartList,
		shopList
	}
	return state
}












const store=createStore(reducer)
export default store;